const Koa = require('koa')
const app = new Koa()
const router = require('koa-router')()
var cors = require('koa-cors')
const axios = require(('axios'))

app.use(cors())

router.get('/login', async (ctx, next) => {
    const code = ctx.request.query.code
    const data = await axios.post('https://github.com/login/oauth/access_token', {
        "client_id" : "client_id",
	    "client_secret": "client_secret",
	    "code": code
    }).then((res) => {
        return res.data
    })
    const access_token = data.split('=')[1].split('&')[0]
    const token_type = data.split('=')[3]
    console.log(data)
    const userInfo = await axios({
        method: 'GET',
        url: `https://api.github.com/user`,
        headers: {
          'Authorization': `${token_type} ${access_token}`
        }
      })
    console.log(userInfo.data)
    ctx.body = userInfo.data
})

app.use(router.routes(), router.allowedMethods())




app.listen(8080, () => {
    console.log('runing on 8080')
})